//package com.tenebrous.jestic.grpc;
//
//import com.google.protobuf.Any;
//import com.tencentcloudapi.cvm.v20170312.models.InstanceStatus;
//import com.tenebrous.jestic.auth.AuthTokenGenerator;
//import com.tenebrous.jestic.entity.server.JesticServer;
//import com.tenebrous.jestic.enums.InstanceStatusEnum;
//import com.tenebrous.jestic.proto.common.GrpcResponse;
//import com.tenebrous.jestic.proto.common.RetCode;
//import com.tenebrous.jestic.proto.connect.ServerAuthorityGrpc;
//import com.tenebrous.jestic.proto.connect.ServerAuthorityServiceGrpc;
//import com.tenebrous.jestic.server.AbstractInstanceContext;
//import com.tenebrous.jestic.server.Instance;
//import com.tenebrous.jestic.server.ServerInstance;
//import com.tenebrous.jestic.service.server.AuthServerService;
//import io.grpc.stub.StreamObserver;
//import lombok.extern.slf4j.Slf4j;
//import net.devh.boot.grpc.server.service.GrpcService;
//
//import javax.annotation.Resource;
//import java.util.Date;
//import java.util.Objects;
//
///**
// * @Description:
// * @Project: grpc-demo
// * @Package: com.tenebrous.grpc.member
// * @Author: zhangya
// * @CreateTime: 2023-05-25  09:58
// * @Version: 1.0.0
// */
//@Slf4j
//@GrpcService
//public class ServerServiceGrpcImpl extends ServerAuthorityServiceGrpc.ServerAuthorityServiceImplBase {
//
//    @Resource
//    private AuthTokenGenerator authToken;
//
//    @Resource
//    private AuthServerService authServerService;
//
//    @Resource
//    private AbstractInstanceContext abstractInstanceContext;
//
//
//
//    @Override
//    public void keepHeartBeat(ServerAuthorityGrpc.ServerHearBeatRequest request, StreamObserver<GrpcResponse> responseObserver) {
//        log.info("jestic [ServerServiceGrpcImpl.keepHeartBeat] recevie new hear beat by [{}]， instance:[{}]", request.getServerName(), request.getInstanceId());
//        JesticServer jesticServer = authServerService.selectServer(request.getServerId(), request.getServerName());
//        GrpcResponse grpcResponse = null;
//        if (Objects.isNull(jesticServer)) {
//            log.info("jestic [ServerServiceGrpcImpl.keepHeartBeat] client [{}] server not found", request.getServerName());
//            ServerAuthorityGrpc.ServerHearBeatResponse response = ServerAuthorityGrpc.ServerHearBeatResponse.newBuilder().setServerResp(false).build();
//            grpcResponse = GrpcResponse.newBuilder().setRetCode(RetCode.BIZ_ERROR).setRetMsg("server not found").setData(Any.pack(response)).build();
//        } else if (jesticServer.getServerStatus() != 1) {
//            log.info("jestic [ServerServiceGrpcImpl.keepHeartBeat] client [{}] status  not abnormal", request.getServerName());
//            ServerAuthorityGrpc.ServerHearBeatResponse response = ServerAuthorityGrpc.ServerHearBeatResponse.newBuilder().setServerResp(false).build();
//            grpcResponse = GrpcResponse.newBuilder().setRetCode(RetCode.BIZ_ERROR).setRetMsg("server status not is running").setData(Any.pack(response)).build();
//        } else {
//            log.info("jestic server accept client[{}] instance:[{}] send heartbeat packet, in healthy state", request.getServerName(), request.getInstanceId());
//            Instance instance = abstractInstanceContext.getInstanceById(request.getInstanceId());
//            if (Objects.isNull(instance)) {
//                log.info("jestic server accept client[{}] instance:[{}] not fount, please try to Auth", request.getServerName(), request.getInstanceId());
//                ServerAuthorityGrpc.ServerHearBeatResponse response = ServerAuthorityGrpc.ServerHearBeatResponse.newBuilder().setServerResp(false).build();
//                grpcResponse = GrpcResponse.newBuilder().setRetCode(RetCode.BIZ_ERROR).setRetMsg("server "+request.getServerName()+" instance not fount, please try to Auth").setData(Any.pack(response)).build();
//            } else {
//                // 维持心跳
//                instance.setRecentlyAuth(new Date().getTime());
//                instance.setTimes(instance.getTimes() + 1);
//                abstractInstanceContext.flushInstance(instance);
//                ServerAuthorityGrpc.ServerHearBeatResponse response = ServerAuthorityGrpc.ServerHearBeatResponse.newBuilder().setServerResp(true).build();
//                grpcResponse = GrpcResponse.newBuilder().setRetCode(RetCode.SUCCESS).setRetMsg("success").setData(Any.pack(response)).build();
//            }
//        }
//        responseObserver.onNext(grpcResponse);
//        responseObserver.onCompleted();
//    }
//
//    @Override
//    public void authority(ServerAuthorityGrpc.ServerAuthorityRequest request, StreamObserver<GrpcResponse> responseObserver) {
//        log.info("jestic [ServerServiceGrpcImpl.authority] server [{}] successfully established connection， request \n[{}]", request.getServerName(), request);
//        String serverId = request.getServerId();
//        String serverName = request.getServerName();
//
//        GrpcResponse grpcResponse = null;
//        // 查询服务
//        JesticServer jesticServer = authServerService.selectServer(serverId, serverName);
//        if (Objects.isNull(jesticServer)) {
//            log.info("jestic [ServerServiceGrpcImpl.authority] client [{}] server not found", request.getServerName());
//            ServerAuthorityGrpc.ServerAuthorityResponse response = ServerAuthorityGrpc.ServerAuthorityResponse.newBuilder().build();
//            grpcResponse = GrpcResponse.newBuilder().setRetCode(RetCode.BIZ_ERROR).setRetMsg("server not found").setData(Any.pack(response)).build();
//        } else if (jesticServer.getServerStatus() != 1) {
//            log.info("jestic [ServerServiceGrpcImpl.authority] client [{}] status  not abnormal", request.getServerName());
//            ServerAuthorityGrpc.ServerAuthorityResponse response = ServerAuthorityGrpc.ServerAuthorityResponse.newBuilder().build();
//            grpcResponse = GrpcResponse.newBuilder().setRetCode(RetCode.BIZ_ERROR).setRetMsg("server status not is running").setData(Any.pack(response)).build();
//        } else {
//            Instance instance = new ServerInstance(abstractInstanceContext.initContext(jesticServer, authToken)).initInstance();
//            log.info("jestic [ServerServiceGrpcImpl.authority] client [{}] init instance:[{}]", request.getServerName(), instance.getInstanceId());
//            // 设置客户端信息
//            instance.setIp(request.getIp());
//            instance.setPort(request.getPort());
//            instance.setGrpcPort(request.getGrpcPort());
//            instance.setInstanceStatus(InstanceStatusEnum.HEALTHY);
//            abstractInstanceContext.flushInstance(instance);
//            // 给与响应
//            ServerAuthorityGrpc.ServerAuthorityResponse response = ServerAuthorityGrpc.ServerAuthorityResponse.newBuilder()
//                    .setId(request.getServerId())
//                    .setInstanceId(instance.getInstanceId())
//                    .setInstanceStatus(InstanceStatus.forNumber(instance.getInstanceStatus().getCode()))
//                    .setToken(instance.getToken())
//                    .setExpire(instance.getExpireTime())
//                    .setIsAuth(true)
//                    .build();
//            // 提示信息
//            grpcResponse = GrpcResponse.newBuilder().setRetCode(RetCode.SUCCESS).setRetMsg("success").setData(Any.pack(response)).build();
//        }
//        responseObserver.onNext(grpcResponse);
//        responseObserver.onCompleted();
//
//    }
//
//    @Override
//    public void serverShutDown(ServerAuthorityGrpc.ServerShutDownRequest request, StreamObserver<GrpcResponse> responseObserver) {
//        log.info("jestic server [{}] shutdown", request.getServerName());
////        boolean verify = authToken.verify(request.getToken());
////        if (verify) {
////            authToken.removeServerInfo(request.getToken());
////        }
//        ServerAuthorityGrpc.ServerShutDownResponse response = ServerAuthorityGrpc.ServerShutDownResponse.newBuilder().setServerResp(true).build();
//        GrpcResponse grpcResponse = GrpcResponse.newBuilder().setRetCode(RetCode.SUCCESS).setRetMsg("success").setData(Any.pack(response)).build();
//        responseObserver.onNext(grpcResponse);
//        responseObserver.onCompleted();
//    }
//}
